package com.cinema.controller;

import com.cinema.model.Movie;
import com.cinema.model.Schedule;
import com.cinema.model.User;
import com.cinema.service.MovieService;
import com.cinema.service.ScheduleService;
import com.cinema.service.TicketService;
import com.cinema.service.UserService;
import com.cinema.util.InputUtil;
import com.cinema.util.StringUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 经理控制器
 * 处理经理相关的操作
 */
public class ManagerController {
    private final UserService userService;
    private final MovieService movieService;
    private final ScheduleService scheduleService;
    private final TicketService ticketService;

    public ManagerController() {
        this.userService = new UserService();
        this.movieService = new MovieService();
        this.scheduleService = new ScheduleService();
        this.ticketService = new TicketService();
    }

    /**
     * 显示经理菜单
     */
    public void showMenu(User manager) {
        boolean running = true;
        
        while (running) {
            displayManagerMenu();
            int choice = InputUtil.readInt("请选择操作: ", 0, 6);
            
            switch (choice) {
                case 1:
                    passwordManagement(manager);
                    break;
                case 2:
                    movieManagement();
                    break;
                case 3:
                    scheduleManagement(manager);
                    break;
                case 4:
                    salesDataManagement();
                    break;
                case 5:
                    System.out.println("正在退出登录...");
                    running = false;
                    break;
                case 0:
                    displayUserInfo(manager);
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 显示经理菜单
     */
    private void displayManagerMenu() {
        System.out.println("\n==================== 经理菜单 ====================");
        System.out.println("1. 密码管理");
        System.out.println("2. 影片管理");
        System.out.println("3. 排片管理");
        System.out.println("4. 销售数据查看");
        System.out.println("5. 退出登录");
        System.out.println("0. 查看个人信息");
        System.out.println("==================================================");
    }

    /**
     * 密码管理
     */
    private void passwordManagement(User manager) {
        boolean running = true;
        
        while (running) {
            System.out.println("\n==================== 密码管理 ====================");
            System.out.println("1. 修改自身密码");
            System.out.println("2. 重置用户密码");
            System.out.println("3. 返回上级菜单");
            System.out.println("==================================================");
            
            int choice = InputUtil.readInt("请选择操作: ", 1, 3);
            
            switch (choice) {
                case 1:
                    changeOwnPassword(manager);
                    break;
                case 2:
                    resetUserPassword(manager);
                    break;
                case 3:
                    running = false;
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 修改自身密码
     */
    private void changeOwnPassword(User manager) {
        System.out.println("\n==================== 修改密码 ====================");
        
        String oldPassword = InputUtil.readNonEmptyString("请输入当前密码: ");
        String newPassword = InputUtil.readNonEmptyString("请输入新密码: ");
        String confirmPassword = InputUtil.readNonEmptyString("请确认新密码: ");
        
        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的密码不一致！");
            InputUtil.pauseForUser();
            return;
        }

        if (userService.changePassword(manager.getUsername(), oldPassword, newPassword)) {
            System.out.println("密码修改成功！");
        } else {
            System.out.println("密码修改失败，请检查当前密码是否正确！");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 重置用户密码
     */
    private void resetUserPassword(User manager) {
        System.out.println("\n==================== 重置用户密码 ====================");
        
        List<User> users = userService.getAllNormalUsers();
        if (users.isEmpty()) {
            System.out.println("当前没有用户！");
            InputUtil.pauseForUser();
            return;
        }

        System.out.println("用户列表：");
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            System.out.printf("%d. %s - %s\n", i + 1, user.getUsername(), user.getPhoneNumber());
        }

        int userChoice = InputUtil.readInt("请选择要重置密码的用户编号 (0取消): ", 0, users.size());
        if (userChoice == 0) {
            return;
        }

        User targetUser = users.get(userChoice - 1);
        boolean confirm = InputUtil.readConfirmation(
                            String.format("确认重置用户 %s 的密码为 123456？", targetUser.getUsername()));
        
        if (confirm) {
            if (userService.resetPassword(manager.getUsername(), targetUser.getUsername())) {
                System.out.println("密码重置成功！新密码为：123456");
                System.out.println("用户下次登录时将被要求修改密码。");
            } else {
                System.out.println("密码重置失败！");
            }
        } else {
            System.out.println("操作已取消。");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 影片管理
     */
    private void movieManagement() {
        boolean running = true;
        
        while (running) {
            System.out.println("\n==================== 影片管理 ====================");
            System.out.println("1. 列出所有影片");
            System.out.println("2. 查询影片信息");
            System.out.println("3. 添加影片");
            System.out.println("4. 修改影片信息");
            System.out.println("5. 删除影片");
            System.out.println("6. 返回上级菜单");
            System.out.println("==================================================");
            
            int choice = InputUtil.readInt("请选择操作: ", 1, 6);
            
            switch (choice) {
                case 1:
                    listAllMovies();
                    break;
                case 2:
                    queryMovies();
                    break;
                case 3:
                    addMovie();
                    break;
                case 4:
                    updateMovie();
                    break;
                case 5:
                    deleteMovie();
                    break;
                case 6:
                    running = false;
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 列出所有影片
     */
    private void listAllMovies() {
        System.out.println("\n" + StringUtil.repeat("=", 100));
        System.out.println("                                     影片列表");
        System.out.println(StringUtil.repeat("=", 100));
        
        List<Movie> movies = movieService.getAllShowingMovies();
        if (movies.isEmpty()) {
            System.out.println("当前没有正在上映的影片！");
        } else {
            displayMovieTable(movies);
        }
        System.out.println(StringUtil.repeat("=", 100));
        InputUtil.pauseForUser();
    }

    /**
     * 查询影片
     */
    private void queryMovies() {
        System.out.println("\n==================== 查询影片 ====================");
        System.out.println("1. 按片名查询");
        System.out.println("2. 按导演查询");
        System.out.println("3. 按主演查询");
        System.out.println("4. 组合查询");
        
        int choice = InputUtil.readInt("请选择查询方式: ", 1, 4);
        List<Movie> results = null;
        
        switch (choice) {
            case 1:
                String title = InputUtil.readString("请输入片名（支持模糊查询）: ");
                results = movieService.searchMovies(title, null, null);
                break;
            case 2:
                String director = InputUtil.readString("请输入导演姓名（支持模糊查询）: ");
                results = movieService.findMoviesByDirector(director);
                break;
            case 3:
                String actor = InputUtil.readString("请输入主演姓名（支持模糊查询）: ");
                results = movieService.findMoviesByActor(actor);
                break;
            case 4:
                String searchTitle = InputUtil.readString("请输入片名（可为空）: ");
                String searchDirector = InputUtil.readString("请输入导演（可为空）: ");
                String searchActor = InputUtil.readString("请输入主演（可为空）: ");
                results = movieService.searchMovies(searchTitle, searchDirector, searchActor);
                break;
        }

        if (results != null) {
            displayMovieSearchResults(results);
        }
        InputUtil.pauseForUser();
    }

    /**
     * 显示影片查询结果
     */
    private void displayMovieSearchResults(List<Movie> movies) {
        if (movies.isEmpty()) {
            System.out.println("未找到符合条件的影片！");
        } else {
            System.out.println("\n" + StringUtil.repeat("=", 100));
            System.out.println("                                   查询结果");
            System.out.println(StringUtil.repeat("=", 100));
            displayMovieTable(movies);
            System.out.println(StringUtil.repeat("=", 100));
        }
    }

    /**
     * 添加影片
     */
    private void addMovie() {
        System.out.println("\n==================== 添加影片 ====================");
        
        String title = InputUtil.readNonEmptyString("请输入片名: ");
        String director = InputUtil.readNonEmptyString("请输入导演: ");
        String actors = InputUtil.readNonEmptyString("请输入主演: ");
        String plot = InputUtil.readNonEmptyString("请输入剧情简介: ");
        int duration = InputUtil.readInt("请输入时长(分钟): ");
        
        if (!movieService.isValidDuration(duration)) {
            System.out.println("时长无效！请输入1-300分钟之间的数值。");
            InputUtil.pauseForUser();
            return;
        }

        double rating = InputUtil.readDouble("请输入评分(0-10): ", 0.0, 10.0);

        if (movieService.addMovie(title, director, actors, plot, duration, rating)) {
            System.out.println("影片添加成功！");
        } else {
            System.out.println("影片添加失败！");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 修改影片信息
     */
    private void updateMovie() {
        System.out.println("\n==================== 修改影片信息 ====================");
        
        String title = InputUtil.readNonEmptyString("请输入要修改的影片名称: ");
        Optional<Movie> movieOpt = movieService.findMovieByTitle(title);
        
        if (!movieOpt.isPresent()) {
            System.out.println("影片不存在！");
            InputUtil.pauseForUser();
            return;
        }

        Movie movie = movieOpt.get();
        System.out.println("当前影片信息：");
        displayMovieSearchResults(Arrays.asList(movie));

        System.out.println("\n请输入新的影片信息：");
        String newTitle = InputUtil.readNonEmptyString("新片名: ");
        String newDirector = InputUtil.readNonEmptyString("新导演: ");
        String newActors = InputUtil.readNonEmptyString("新主演: ");
        String newPlot = InputUtil.readNonEmptyString("新剧情简介: ");
        int newDuration = InputUtil.readInt("新时长(分钟): ");
        
        if (!movieService.isValidDuration(newDuration)) {
            System.out.println("时长无效！请输入1-300分钟之间的数值。");
            InputUtil.pauseForUser();
            return;
        }

        double newRating = InputUtil.readDouble("新评分(0-10): ", 0.0, 10.0);

        if (movieService.updateMovie(movie.getMovieId(), newTitle, newDirector, newActors, newPlot, newDuration, newRating)) {
            System.out.println("影片信息修改成功！");
        } else {
            System.out.println("影片信息修改失败！");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 删除影片
     */
    private void deleteMovie() {
        System.out.println("\n==================== 删除影片 ====================");
        
        String title = InputUtil.readNonEmptyString("请输入要删除的影片名称: ");
        Optional<Movie> movieOpt = movieService.findMovieByTitle(title);
        
        if (!movieOpt.isPresent()) {
            System.out.println("影片不存在！");
            InputUtil.pauseForUser();
            return;
        }

        Movie movie = movieOpt.get();
        System.out.println("要删除的影片信息：");
        displayMovieSearchResults(Arrays.asList(movie));

        System.out.println("\n⚠️  警告：删除后无法恢复！");
        boolean confirm = InputUtil.readConfirmation("确认删除影片 " + movie.getTitle() + "？");
        
        if (confirm) {
            if (movieService.deleteMovie(movie.getMovieId())) {
                System.out.println("影片删除成功！");
            } else {
                System.out.println("影片删除失败！可能是该影片已有排片。");
            }
        } else {
            System.out.println("操作已取消。");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 排片管理
     */
    private void scheduleManagement(User manager) {
        boolean running = true;
        
        while (running) {
            System.out.println("\n==================== 排片管理 ====================");
            System.out.println("1. 列出所有场次");
            System.out.println("2. 增加场次");
            System.out.println("3. 修改场次");
            System.out.println("4. 删除场次");
            System.out.println("5. 自动排片");
            System.out.println("6. 返回上级菜单");
            System.out.println("==================================================");
            
            int choice = InputUtil.readInt("请选择操作: ", 1, 6);
            
            switch (choice) {
                case 1:
                    listSchedules();
                    break;
                case 2:
                    addSchedule();
                    break;
                case 3:
                    updateSchedule(manager);
                    break;
                case 4:
                    deleteSchedule(manager);
                    break;
                case 5:
                    autoSchedule();
                    break;
                case 6:
                    running = false;
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 列出场次
     */
    private void listSchedules() {
        System.out.println("\n==================== 场次列表 ====================");
        System.out.println("1. 当日场次");
        System.out.println("2. 近3日场次");
        System.out.println("3. 近一周场次");
        
                    int choice = InputUtil.readInt("请选择: ", 1, 3);
        List<Schedule> schedules = null;
        
        switch (choice) {
            case 1:
                schedules = scheduleService.getTodaySchedules();
                break;
            case 2:
                schedules = scheduleService.getThreeDaysSchedules();
                break;
            case 3:
                schedules = scheduleService.getWeekSchedules();
                break;
        }

        if (schedules != null) {
            displaySchedules(schedules);
        }
        InputUtil.pauseForUser();
    }

    /**
     * 显示场次列表
     */
    private void displaySchedules(List<Schedule> schedules) {
        if (schedules.isEmpty()) {
            System.out.println("没有找到场次信息！");
        } else {
            System.out.println("\n" + StringUtil.repeat("=", 95));
            System.out.println("                                场次列表");
            System.out.println(StringUtil.repeat("=", 95));
            
            System.out.printf("%-10s %-24s %-8s %-16s %8s %12s\n", 
                "场次ID", "影片", "放映厅", "放映时间", "票价", "座位情况");
            System.out.println(StringUtil.repeat("-", 95));
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm");
            for (Schedule schedule : schedules) {
                Optional<Movie> movieOpt = movieService.findMovieById(schedule.getMovieId());
                String movieTitle = movieOpt.map(Movie::getTitle).orElse("未知影片");
                String formattedTitle = formatChineseString(movieTitle, 22);
                
                System.out.printf("%-10s %-24s %-8s %-16s %8.2f %12s\n",
                    schedule.getScheduleId() != null && schedule.getScheduleId().length() >= 8 
                        ? schedule.getScheduleId().substring(0, 8) 
                        : (schedule.getScheduleId() != null ? schedule.getScheduleId() : "N/A"),
                    formattedTitle,
                    schedule.getHallId(),
                    schedule.getShowTime().format(formatter),
                    schedule.getPrice(),
                    schedule.getAvailableSeats() + "/" + schedule.getTotalSeats());
            }
            System.out.println(StringUtil.repeat("=", 95));
        }
    }

    /**
     * 添加场次
     */
    private void addSchedule() {
        System.out.println("\n==================== 添加场次 ====================");
        
        // 显示可用影片
        List<Movie> movies = movieService.getAllShowingMovies();
        if (movies.isEmpty()) {
            System.out.println("没有可用的影片！请先添加影片。");
            InputUtil.pauseForUser();
            return;
        }

        System.out.println("可用影片列表：");
        for (int i = 0; i < movies.size(); i++) {
            Movie movie = movies.get(i);
            System.out.printf("%d. %s (%d分钟)\n", i + 1, movie.getTitle(), movie.getDuration());
        }

        int movieChoice = InputUtil.readInt("请选择影片编号: ", 1, movies.size());
        Movie selectedMovie = movies.get(movieChoice - 1);

        // 显示可用放映厅
        String[] halls = scheduleService.getAvailableCinemaHalls();
        System.out.println("\n可用放映厅：");
        for (int i = 0; i < halls.length; i++) {
            System.out.printf("%d. %s\n", i + 1, halls[i]);
        }

        int hallChoice = InputUtil.readInt("请选择放映厅编号: ", 1, halls.length);
        String selectedHall = halls[hallChoice - 1];

        LocalDateTime showTime = InputUtil.readDateTime("请输入放映时间");
        double price = InputUtil.readDouble("请输入票价: ");

        if (scheduleService.addSchedule(selectedMovie.getMovieId(), selectedHall, showTime, price, 10, 12)) {
            System.out.println("场次添加成功！");
        } else {
            System.out.println("场次添加失败！可能存在时间冲突或时间超出一周范围。");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 修改场次
     */
    private void updateSchedule(User manager) {
        System.out.println("\n==================== 修改场次 ====================");
        
        List<Schedule> schedules = scheduleService.getWeekSchedules();
        if (schedules.isEmpty()) {
            System.out.println("没有可修改的场次！");
            InputUtil.pauseForUser();
            return;
        }

        displaySchedules(schedules);
        
        String scheduleId = InputUtil.readNonEmptyString("请输入要修改的场次ID: ");
        Optional<Schedule> scheduleOpt = scheduleService.findScheduleById(scheduleId);
        
        if (!scheduleOpt.isPresent()) {
            System.out.println("场次不存在！");
            InputUtil.pauseForUser();
            return;
        }

        // 显示可用影片
        List<Movie> movies = movieService.getAllShowingMovies();
        System.out.println("可用影片列表：");
        for (int i = 0; i < movies.size(); i++) {
            Movie movie = movies.get(i);
            System.out.printf("%d. %s\n", i + 1, movie.getTitle());
        }

        int movieChoice = InputUtil.readInt("请选择新影片编号: ", 1, movies.size());
        Movie selectedMovie = movies.get(movieChoice - 1);

        LocalDateTime newShowTime = InputUtil.readDateTime("请输入新的放映时间");
        double newPrice = InputUtil.readDouble("请输入新的票价: ");

        if (scheduleService.updateSchedule(manager.getUsername(), scheduleId, 
                                         selectedMovie.getMovieId(), newShowTime, newPrice)) {
            System.out.println("场次修改成功！");
        } else {
            System.out.println("场次修改失败！可能该场次已有售票。");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 删除场次
     */
    private void deleteSchedule(User manager) {
        System.out.println("\n==================== 删除场次 ====================");
        
        List<Schedule> schedules = scheduleService.getWeekSchedules();
        if (schedules.isEmpty()) {
            System.out.println("没有可删除的场次！");
            InputUtil.pauseForUser();
            return;
        }

        displaySchedules(schedules);
        
        String scheduleId = InputUtil.readNonEmptyString("请输入要删除的场次ID: ");
        Optional<Schedule> scheduleOpt = scheduleService.findScheduleById(scheduleId);
        
        if (!scheduleOpt.isPresent()) {
            System.out.println("场次不存在！");
            InputUtil.pauseForUser();
            return;
        }

        Schedule schedule = scheduleOpt.get();
        Optional<Movie> movieOpt = movieService.findMovieById(schedule.getMovieId());
        String movieTitle = movieOpt.map(Movie::getTitle).orElse("未知影片");

        System.out.println("要删除的场次信息：");
        System.out.println("影片：" + movieTitle);
        System.out.println("放映厅：" + schedule.getHallId());
        System.out.println("放映时间：" + schedule.getShowTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));

        boolean confirm = InputUtil.readConfirmation("确认删除该场次？");
        
        if (confirm) {
            if (scheduleService.deleteSchedule(manager.getUsername(), scheduleId)) {
                System.out.println("场次删除成功！");
            } else {
                System.out.println("场次删除失败！可能该场次已有售票。");
            }
        } else {
            System.out.println("操作已取消。");
        }
        InputUtil.pauseForUser();
    }

    /**
     * 自动排片
     */
    private void autoSchedule() {
        System.out.println("\n==================== 自动排片 ====================");
        
        LocalDateTime startDate = InputUtil.readDateTime("请输入开始日期");
        LocalDateTime endDate = InputUtil.readDateTime("请输入结束日期");
        
        if (endDate.isBefore(startDate)) {
            System.out.println("结束日期不能早于开始日期！");
            InputUtil.pauseForUser();
            return;
        }

        System.out.println("正在进行自动排片...");
        List<Schedule> newSchedules = scheduleService.autoSchedule(startDate, endDate);
        
        System.out.println("自动排片完成！共生成 " + newSchedules.size() + " 个场次。");
        
        if (!newSchedules.isEmpty() && InputUtil.readConfirmation("是否查看生成的场次？")) {
            displaySchedules(newSchedules);
        }
        
        InputUtil.pauseForUser();
    }

    /**
     * 销售数据管理
     */
    private void salesDataManagement() {
        boolean running = true;
        
        while (running) {
            System.out.println("\n==================== 销售数据查看 ====================");
            System.out.println("1. 当日销售数据");
            System.out.println("2. 当周销售数据");
            System.out.println("3. 当月销售数据");
            System.out.println("4. 返回上级菜单");
            System.out.println("======================================================");
            
            int choice = InputUtil.readInt("请选择操作: ", 1, 4);
            
            switch (choice) {
                case 1:
                    displaySalesData(ticketService.getTodaySales(), "当日");
                    break;
                case 2:
                    displaySalesData(ticketService.getWeekSales(), "当周");
                    break;
                case 3:
                    displaySalesData(ticketService.getMonthSales(), "当月");
                    break;
                case 4:
                    running = false;
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    /**
     * 显示销售数据
     */
    private void displaySalesData(TicketService.SalesData salesData, String period) {
        System.out.println("\n==================== " + period + "销售数据 ====================");
        System.out.println(salesData.toString());
        InputUtil.pauseForUser();
    }

    /**
     * 显示个人信息
     */
    private void displayUserInfo(User manager) {
        System.out.println("\n==================== 个人信息 ====================");
        System.out.println("用户ID：" + manager.getUserId());
        System.out.println("用户名：" + manager.getUsername());
        System.out.println("用户类型：" + manager.getUserType().getDescription());
        System.out.println("手机号：" + manager.getPhoneNumber());
        System.out.println("注册时间：" + manager.getRegistrationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        InputUtil.pauseForUser();
    }

    /**
     * 截断字符串
     */
    private String truncateString(String str, int maxLength) {
        if (str == null) return "";
        return str.length() > maxLength ? str.substring(0, maxLength - 3) + "..." : str;
    }
    
    /**
     * 格式化中文字符串，考虑中文字符的显示宽度
     */
    private String formatChineseString(String str, int maxDisplayWidth) {
        if (str == null) return "";
        
        int displayWidth = 0;
        StringBuilder result = new StringBuilder();
        
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int charWidth = isChinese(c) ? 2 : 1; // 中文字符占2个位置，英文字符占1个位置
            
            if (displayWidth + charWidth > maxDisplayWidth) {
                if (maxDisplayWidth >= 3) {
                    // 如果还有空间，添加省略号
                    if (displayWidth <= maxDisplayWidth - 3) {
                        result.append("...");
                    } else {
                        // 替换最后几个字符为省略号
                        while (result.length() > 0 && displayWidth > maxDisplayWidth - 3) {
                            char lastChar = result.charAt(result.length() - 1);
                            result.deleteCharAt(result.length() - 1);
                            displayWidth -= isChinese(lastChar) ? 2 : 1;
                        }
                        result.append("...");
                    }
                }
                break;
            }
            
            result.append(c);
            displayWidth += charWidth;
        }
        
        // 添加空格填充到指定宽度
        while (displayWidth < maxDisplayWidth) {
            result.append(" ");
            displayWidth++;
        }
        
        return result.toString();
    }
    
    /**
     * 判断字符是否为中文字符
     */
    private boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FFF;
    }
    
    /**
     * 显示影片表格，优化中文字符对齐
     */
    private void displayMovieTable(List<Movie> movies) {
        // 定义列宽（按显示宽度计算）
        int titleWidth = 24;     // 片名列宽度
        int directorWidth = 16;  // 导演列宽度
        int actorsWidth = 36;    // 主演列宽度
        int durationWidth = 12;  // 时长列宽度
        int ratingWidth = 8;     // 评分列宽度
        
        // 打印表头
        String titleHeader = padToDisplayWidth("片名", titleWidth);
        String directorHeader = padToDisplayWidth("导演", directorWidth);
        String actorsHeader = padToDisplayWidth("主演", actorsWidth);
        String durationHeader = padToDisplayWidth("时长(分钟)", durationWidth);
        String ratingHeader = padToDisplayWidth("评分", ratingWidth);
        
        System.out.println(titleHeader + directorHeader + actorsHeader + durationHeader + ratingHeader);
        System.out.println(StringUtil.repeat("-", titleWidth + directorWidth + actorsWidth + durationWidth + ratingWidth));
        
        // 打印影片信息
        for (Movie movie : movies) {
            String title = truncateAndPadToDisplayWidth(movie.getTitle(), titleWidth);
            String director = truncateAndPadToDisplayWidth(movie.getDirector(), directorWidth);
            String actors = truncateAndPadToDisplayWidth(movie.getActors(), actorsWidth);
            String duration = padToDisplayWidth(String.valueOf(movie.getDuration()), durationWidth);
            String rating = padToDisplayWidth(String.format("%.1f", movie.getRating()), ratingWidth);
            
            System.out.println(title + director + actors + duration + rating);
        }
    }
    
    /**
     * 将字符串填充到指定的显示宽度，右侧用空格填充
     */
    private String padToDisplayWidth(String str, int targetDisplayWidth) {
        if (str == null) str = "";
        
        int currentDisplayWidth = getDisplayWidth(str);
        if (currentDisplayWidth >= targetDisplayWidth) {
            return str;
        }
        
        StringBuilder result = new StringBuilder(str);
        while (currentDisplayWidth < targetDisplayWidth) {
            result.append(" ");
            currentDisplayWidth++;
        }
        
        return result.toString();
    }
    
    /**
     * 截断字符串到指定显示宽度，并用空格填充
     */
    private String truncateAndPadToDisplayWidth(String str, int targetDisplayWidth) {
        if (str == null) str = "";
        
        int currentDisplayWidth = 0;
        StringBuilder result = new StringBuilder();
        
        // 截断超长字符串
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int charWidth = isChinese(c) ? 2 : 1;
            
            if (currentDisplayWidth + charWidth > targetDisplayWidth - 2) {
                // 如果剩余空间不足，添加省略号
                if (targetDisplayWidth >= 2 && currentDisplayWidth <= targetDisplayWidth - 2) {
                    result.append("..");
                    currentDisplayWidth += 2;
                }
                break;
            }
            
            result.append(c);
            currentDisplayWidth += charWidth;
        }
        
        // 填充到目标宽度
        while (currentDisplayWidth < targetDisplayWidth) {
            result.append(" ");
            currentDisplayWidth++;
        }
        
        return result.toString();
    }
    
    /**
     * 计算字符串的显示宽度
     */
    private int getDisplayWidth(String str) {
        if (str == null) return 0;
        
        int width = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            width += isChinese(c) ? 2 : 1;
        }
        return width;
    }
}